<?php

namespace api\modules\user\models;

use Yii;
use yii\data\ActiveDataProvider;
use common\models\user\UserSignin;

class SigninSearch extends UserSignin {
    private $_token;

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params = []) {
        if (!isset($params['date'])) {
            $beginDate = date('Y-m-01', time());
            $endDate = date('Y-m-d', strtotime("$beginDate + 1 month -1 day"));

        } else {
            $beginDate = date('Y-m-01', strtotime($params['date']));
            $endDate = date('Y-m-d', strtotime("$beginDate + 1 month -1 day"));
        }

        $query = static::find()->where([
            'user_id' => $this->_token->user_id,
        ])
            ->andWhere(['between', 'date', $beginDate, $endDate])
            ->asArray()
            ->orderBy('date desc')
            ->all();
        $today = date('Y-m-d');

        $checkin = static::find()->where(['user_id' => $this->_token->user_id, 'date' => $today])->exists();

        if (count($query)) {

            $count = static::find()
                ->select("count(id) as cnt")
                ->where(['date' => date('Y-m-d')])
                ->andWhere(['<=', 'created_at', $query[0]['created_at']])
                ->andWhere(['<', 'id', $query[0]['id']])
                ->asArray()
                ->one();

            $count = $count['cnt'];

            if ($checkin) {
                $count += 1;
            }

            return [
                'dates' => array_column($query, 'date'),
                'continuation' => $query[0]['continuation'],
                'count' => (int)$count,
                'checkedin' => (bool)$checkin
            ];
        }
        return [
            'dates' => [],
            'continuation' => 0,
            'count' => 0,
            'checkin' => $checkin,
        ];
    }

    public function setToken($token) {
        $this->_token = $token;
        return $this;
    }

}